package ControlLayer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;

import DBLayer.DBConnection;
import DBLayer.DBRoomType;
import DBLayer.IFDBRoomType;
import ModelLayer.KeyWord;
import ModelLayer.Room;
import ModelLayer.RoomType;

public class RoomTypeCtr {
	private RoomCtr roomCtr;

	public RoomTypeCtr() {
		roomCtr = new RoomCtr();
	}

	public RoomType getRoomType(int rtId) {
		IFDBRoomType dbRoomType = new DBRoomType();
		return dbRoomType.getRoomType(rtId);
	}

	public int insertRoomType(String name, double price, int size) {
		RoomType rt = new RoomType();
		int rtId = 0;
		rt.setName(KeyWord.valueOf(name));
		rt.setPricePerNight(price);
		rt.setSize(size);
		// try {
		// DBConnection.startTransaction();
		IFDBRoomType dbRoomType = new DBRoomType();
		rtId = dbRoomType.insertRoomType(rt);
		// DBConnection.commitTransaction();
		// } catch (Exception e) {
		// DBConnection.rollbackTransaction();
		// }
		return rtId;
	}

	public int updateRoomType(int rtId, String name, double price, int size) {
		RoomType rt = new RoomType();
		rt.setId(rtId);
		rt.setName(KeyWord.valueOf(name));
		rt.setPricePerNight(price);
		rt.setSize(size);
		IFDBRoomType dbRoomType = new DBRoomType();
		return dbRoomType.updateRoomType(rt);
	}

	public int deleteRoomType(int rtId) {
		IFDBRoomType dbRoomType = new DBRoomType();
		return dbRoomType.deleteRoomType(rtId);
	}

	public LinkedList<RoomType> getAllRoomType() {
		IFDBRoomType dbRoomType = new DBRoomType();
		return dbRoomType.getAllRoomType();
	}

	public ArrayList<Integer> getAllRoomTypeIds() {
		ArrayList<Integer> rtIds = new ArrayList<Integer>();
		LinkedList<RoomType> rts = getAllRoomType();
		for (RoomType rt : rts) {
			rtIds.add(rt.getId());
		}
		return rtIds;
	}

	public Room getFirstAvailableRoom(int rtId) {
		LinkedList<Room> rooms = roomCtr.getRoomsForRT(rtId);
		for (Room room : rooms) {
			if (room.getEndDate() == null) {
				return room;
			} else if (room.getEndDate().before(
					Calendar.getInstance().getTime()))
				return room;
		}
		return null;
	}

}
